import asyncio
from auth.login_manager import LoginManager
from models.group_store import GroupStore
from models.uploader import Uploader
from handlers.message_handler import register_handlers
from utils.heartbeat import heartbeat_loop
from utils.lifecycle import LifecycleManager
from utils.logger import setup_logger
from telethon.tl.types import Channel, Chat
from telethon.utils import get_peer_id
from utils.auto_retry import auto_retry

log = setup_logger(__name__)

@auto_retry()
async def refresh_groups_and_channels(client, store: GroupStore):
    print("[DEBUG] 进入函数: refresh_groups_and_channels")
    dialogs = await client.get_dialogs()
    print(f"[DEBUG] 总共获取到 {len(dialogs)} 个对话")
    
    all_items = []
    
    for d in dialogs:
        # 检测群组和频道
        if isinstance(d.entity, (Channel, Chat)):
            marked_id = get_peer_id(d.entity)
            
            if d.is_group:
                item_type = '群组'
                print(f"[DEBUG] 发现群组: {d.title} (ID: {d.entity.id}, 标记ID: {marked_id})")
            elif d.is_channel:
                item_type = '频道'
                print(f"[DEBUG] 发现频道: {d.title} (ID: {d.entity.id}, 标记ID: {marked_id})")
            else:
                continue  # 跳过其他类型
            
            # 取第一条消息作为 baseline
            print(f"[DEBUG] 获取{item_type} {d.title} 的最新消息ID作为baseline")
            async for msg in client.iter_messages(d.entity, limit=1):
                baseline = msg.id
                break
            else:
                baseline = 0
            
            # 构建项目信息
            item_info = {
                'id': marked_id,
                'title': d.title,
                'type': item_type,
                'baseline': baseline
            }
            all_items.append(item_info)
    
    print(f"[DEBUG] 总共发现 {len(all_items)} 个群组/频道")
    
    # 将所有群组/频道信息存储到数据库
    if all_items:
        print(f"[DEBUG] 将 {len(all_items)} 个群组/频道信息存储到数据库")
        store.upsert_groups(all_items)
        log.info('stored %s groups/channels to database', len(all_items))
        
        # 显示存储的项目
        for item in all_items:
            print(f"[DEBUG] - 存储{item['type']}: {item['title']} (ID: {item['id']}, baseline: {item['baseline']})")
    else:
        print("[DEBUG] 没有发现任何群组/频道")
    
    return all_items

async def main():
    """主函数"""
    print(f"[DEBUG] 进入函数: main")
    lm = LoginManager()
    # 账号登陆初始化
    if not await lm.login():
        return
    client = lm.client

    # kafka数据库初始化和oss服务器初始化
    uploader = Uploader()
    # 数据库连接初始化
    store = GroupStore()
    # 这个也是在初始化数据库

    # 刷新群组和频道列表，获取所有当前可用的群组和频道（包括新的和已存在的）
    groups = await refresh_groups_and_channels(client=client, store=store)
    
    if not groups:
        print("[DEBUG] 警告: 没有发现任何群组或频道，请检查是否已加入群组或订阅频道")
        return
    
    print(f"[DEBUG] 最终监听的群组/频道列表:")
    for group in groups:
        group_type = group.get('type', '未知')
        print(f"[DEBUG] - {group_type}: {group['title']} (ID: {group['id']}, baseline: {group['baseline']})")

    register_handlers(client=client, groups=groups, uploader=uploader, store=store)
    
    async with LifecycleManager([heartbeat_loop(client=client)]):
        await client.run_until_disconnected()

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n程序已退出")
    except Exception as e:
        print(f"程序发生错误: {e}")

